var express = require('express');
var router = express.Router();
const query = require('../../utils/mysql');
const Result = require('../../utils/api');
var checkAuth = require('../../utils/checkAuth')

//分类列表接口
router.post('/article/category', checkAuth, async function (req, res, next) {
    if (JSON.stringify(req.body) == "{}") {
        // 查询所有的分类
        let sql = 'SELECT * FROM blog_category WHERE is_del = 0'
        let cate = await query(sql)
        let newCate = cate.map(current => {
            return {
                id: current.id,
                value: current.cate_name
            }
        })
        Result.success(res, {
            data: newCate
        })
    } else {
        // 分页查询
        let sql = 'SELECT * FROM blog_category WHERE is_del = ? LIMIT ?,?'
        let sqlArr = [0, (req.body.page - 1) * req.body.limit, req.body.limit]

        let countSql = 'SELECT COUNT(*) AS count FROM blog_category WHERE is_del = ?'
        let countArr = [0]

        let count = await query(countSql, countArr)
        let cates = await query(sql, sqlArr)
        cates.forEach(element => {
            element.is_show = element.is_show == 1 ? true : false;
            element.is_edit = false;
        });
        Result.success(res, {
            count: count[0].count,
            data: cates
        })
    }
})

//分类显示
router.post('/article/category/change', checkAuth, async function (req, res, next) {
    let sql = 'UPDATE blog_category SET is_show = ? WHERE id = ?'
    let sqlArr = [req.body.is_show, req.body.id]
    query(sql, sqlArr).then(() => {
        // console.log("sucess")
        Result.success(res, "SUCCESS", "操作成功")
    }).catch(err => {
        // console.log("fail")
        Result.fail(res, "操作失败")
    })
})

//分类修改
router.post('/article/category/update', checkAuth, async function (req, res, next) {
    let sql = 'UPDATE blog_category SET cate_name = ? WHERE id = ?'

    let sqlArr = [req.body.cate_name, req.body.id]

    let resJson = await query(sql, sqlArr)
    if (resJson.affectedRows == 1) {
        Result.success(res, "SUCCESS", "修改成功")
    } else {
        Result.fail(res, "操作失败")
    }
})

//分类删除
router.post('/article/category/delete', checkAuth, async function (req, res, next) {

    let sql = 'UPDATE blog_category SET is_del = 1 WHERE id = ?'
    let sqlArr = [req.body.id]
    let resJson = await query(sql, sqlArr)
    if (resJson.affectedRows == 1) {
        Result.success(res, "SUCCESS", "删除成功")
    } else {
        Result.fail(res, "操作失败")
    }
})

//标签列表接口
router.post('/article/tag', checkAuth, async function (req, res, next) {
    if (JSON.stringify(req.body) == "{}") {
        // 查询所有的分类
        let sql = 'SELECT * FROM blog_tag WHERE is_del = 0'
        let cate = await query(sql)
        let newCate = cate.map(current => {
            return {
                value: current.id,
                label: current.tag_name
            }
        })
        Result.success(res, {
            data: newCate
        })
    } else {
        // 分页查询
        let sql = 'SELECT * FROM blog_tag WHERE is_del = ? LIMIT ?,?'
        let sqlArr = [0, (req.body.page - 1) * req.body.limit, req.body.limit]

        let countSql = 'SELECT COUNT(*) AS count FROM blog_tag WHERE is_del = ?'
        let countArr = [0]

        let count = await query(countSql, countArr)
        let cates = await query(sql, sqlArr)
        cates.forEach(element => {
            element.is_show = element.is_show == 1 ? true : false;
            element.is_edit = false;
        });
        Result.success(res, {
            count: count[0].count,
            data: cates
        })
    }
})

//标签显示
router.post('/article/tag/change', checkAuth, async function (req, res, next) {
    let sql = 'UPDATE blog_tag SET is_show = ? WHERE id = ?'
    let sqlArr = [req.body.is_show, req.body.id]
    query(sql, sqlArr).then(() => {
        // console.log("sucess")
        Result.success(res, "SUCCESS", "操作成功")
    }).catch(err => {
        // console.log("fail")
        Result.fail(res, "操作失败")
    })
})

//标签修改
router.post('/article/tag/update', checkAuth, async function (req, res, next) {
    let sql = 'UPDATE blog_tag SET tag_name = ? WHERE id = ?'
    let sqlArr = [req.body.tag_name, req.body.id]
    let resJson = await query(sql, sqlArr)
    if (resJson.affectedRows == 1) {
        Result.success(res, "SUCCESS", "修改成功")
    } else {
        Result.fail(res, "操作失败")
    }
})

//标签删除
router.post('/article/tag/delete', checkAuth, async function (req, res, next) {
    let sql = 'UPDATE blog_tag SET is_del = 1 WHERE id = ?'
    let sqlArr = [req.body.id]
    let resJson = await query(sql, sqlArr)
    if (resJson.affectedRows == 1) {
        Result.success(res, "SUCCESS", "删除成功")
    } else {
        Result.fail(res, "操作失败")
    }
})

// 文章是否置顶
router.post('/article/top/change', checkAuth, async function (req, res, next) {
    let rq = req.body
    let sql = 'UPDATE blog_article SET is_top = ? WHERE id = ?'
    let sqlArr = [rq.is_top, rq.id]

    query(sql, sqlArr).then(() => {
        Result.success(res, "SUCCESS", "操作成功")
    }).catch(() => {
        Result.fail(res, "操作失败")
    })
})

// 文章是否发表
router.post('/article/publish/change', checkAuth, function (req, res, next) {
    let rq = req.body
    let sql = 'UPDATE blog_article SET is_publish = ? WHERE id = ?'
    let sqlArr = [rq.is_publish, rq.id]

    query(sql, sqlArr).then(() => {
        Result.success(res, "SUCCESS", "操作成功")
    }).catch(err => {
        Result.fail(res, "操作失败")
    })
})
// 文章删除
router.get('/article/delete/:id', checkAuth, function (req, res, next) {
    let rq = req.params
    console.log(rq, "RQ")
    let sql = 'UPDATE blog_article SET is_del = ? WHERE id = ?'
    let sqlArr = [1, rq.id]

    query(sql, sqlArr).then(() => {
        Result.success(res, "SUCCESS", "删除成功")
    }).catch(() => {
        Result.fail(res, "删除失败")
    })
})

// 文章详情
router.get('/article/:id', checkAuth, async function (req, res, next) {
    let rq = req.params

    let sql = "SELECT * FROM blog_article WHERE id = ?"
    let sqlArr = [rq.id]

    let tagSql = "SELECT tid FROM blog_article_tag WHERE aid = ?"

    let tagArr = await query(tagSql, sqlArr)
    let data = await query(sql, sqlArr)
    let cateSql = 'SELECT cate_name FROM blog_category WHERE id = ?'
    let cateSqlArr = [data[0].cid]
    let [{
        cate_name
    }] = await query(cateSql, cateSqlArr)
    let tags = tagArr.map(current => current.tid)
    // console.log(tags)
    let res1 = {
        id: data[0].id,
        category: cate_name,
        article_title: data[0].article_title,
        article_content: data[0].article_content,
        is_publish: data[0].is_publish,
        type: data[0].type,
        tags: tags
    }
    Result.success(res, res1)
})

//文章列表接口
router.post('/article/list', checkAuth, async function (req, res, next) {

    let sql = 'SELECT * FROM blog_article WHERE is_del = ? LIMIT ?,?'

    let sqlArr = [0, (req.body.page - 1) * req.body.limit, req.body.limit]

    let countSql = 'SELECT COUNT(*) AS count FROM blog_article WHERE is_del = 0'

    let articles = await query(sql, sqlArr)
    let count = await query(countSql)
    // console.log(articles, "ARTICL")

    articles.forEach(current => {
        current.is_publish = current.is_publish == 1 ? true : false;
        current.is_top = current.is_top == 1 ? true : false;
    })

    Result.success(res, {
        count: count[0].count,
        data: articles
    })
})

//文章添加
router.post('/article/save', checkAuth, async function (req, res, next) {
    // console.log(req.body, "BODY")
    let para = req.body,
        id = 0,
        cid = 0,
        article_pic = 'https://cdn.jsdelivr.net/gh/1287969865/github-gos@master/wp-content/uploads/2020/10/249-1024x461.jpg';

    try {
        // 处理分类
        let cateSql = 'SELECT * FROM blog_category WHERE cate_name = ? AND is_del = 0'
        let cateSqlArr = [para.category]

        let cates = await query(cateSql, cateSqlArr)
        // console.log(cates, "CATES")
        if (cates.length !== 0) {
            cid = cates[0].id
        } else {
            let sql = 'INSERT INTO blog_category (cate_name, is_show, is_del, add_time) VALUES (?,?,?,?)'
            let sqlArr = [para.category, 1, 0, new Date()]
            let cateId = await query(sql, sqlArr)
            cid = cateId.insertId
        }

        if (para.id === 0) {
            // 新增文章
            let sql = 'INSERT INTO blog_article ( cid, article_title, article_pic, article_content, add_time, mod_time, is_publish, visit, type ) VALUES ( ?,?,?,?,?,?,?,?,? )'
            let sqlArr = [cid, para.article_title, article_pic, para.article_content, new Date(), new Date(), para.is_publish, 0, para.type]

            let articleId = await query(sql, sqlArr)
            id = articleId.insertId
        } else {
            id = para.id
            // 更新文章
            let sql = 'UPDATE blog_article SET cid = ?, article_title = ?, article_content = ?, mod_time = ?, is_publish = ?, type = ? WHERE id = ?'
            let sqlArr = [cid, para.article_title, para.article_content, new Date(), para.is_publish, para.type, id]
            await query(sql, sqlArr)

            let tagSql = 'DELETE FROM blog_article_tag WHERE aid = ?'
            let aid = [id]
            await query(tagSql, aid)
        }
        //标签处理
        let tids = await Promise.all(para.tags.map(async (current) => {
            if (typeof current === 'number') {
                return current
            } else {
                let sql = 'INSERT INTO blog_tag ( tag_name, is_show, is_del, add_time ) VALUES ( ?,?,?,? )'
                let sqlArr = [current, 1, 0, new Date()]
                let tid = await query(sql, sqlArr)
                return tid.insertId
            }
        }))
        // 标签插入数据表
        tids.forEach(async (current) => {
            let tagSql = 'INSERT INTO blog_article_tag ( aid, tid, add_time ) VALUES ( ?,?,? )'
            let tagSqlArr = [id, current, new Date()]
            await query(tagSql, tagSqlArr)
        })

        Result.success(res, "SUCCESS", "保存成功")
    } catch (error) {

        console.log(error)
        Result.fail(res, "操作失败")
    }
})

module.exports = router;